<?php
			
	/* SVN FILE: $Id: fnInputs.php 8 2011-03-13 08:32:38Z michele.andreoletti@gmail.com $ */
	
	/**
	 * Project Name : arcadia
	 *
	 * @author $Author: michele.andreoletti@gmail.com $
	 * @version $Revision: 8 $
	 * @lastrevision $Date: 2011-03-13 08:32:38 +0000 (Sun, 13 Mar 2011) $
	 * @filesource $URL: http://arcadia.googlecode.com/svn/trunk/include/fnInputs.php $
	 */
	 
	 
	/**
	 * fnTextInput
	 * <input type='text' />
	 * 
	 * @param $sField	utilizzato per gli attributi 'name' e 'id' del campo di input
	 * @param $sType	riferito al type del campo di input (ovvero: 'text', 'password', 'hidden')
	 *
	 */
	function fnTextInput ($sField, $sLabel, $aData, $sSize='25', $sType='text', $sMore='') {

		global $sAction, $sViewItemLink, $iTab;
		
		$iAccessLvl = fnGetAccessLvl();
		$iFieldAccessLvl = fnFieldAccessLvl($iAccessLvl, $sViewItemLink, $iTab, $sField);

		$html = '';

		/**
		 * MEMO:
		 * $aFieldsDataType ['date'] [] = $aRow['Field'];
		 * $aFieldsDataType ['text'] [] = $aRow['Field'];
		 * $aFieldsDataType ['currency'] [] = $sField;
		 *
		 */
		 
		if (is_allowed('view', $iFieldAccessLvl)) {
		
			if (fnCheckFieldsDataType($sField, 'date')) {
				$sSize = '12';
				if (!is_array($aData) || !isset($aData[$sField]) || empty($aData[$sField]) || $aData[$sField] == '0000-00-00') {
					$sValue = ($sAction != 'edit' ? '&nbsp;' : '');
				} else  {
					$sValue = date_convert($aData[$sField], 'html');
				}
				
				if (isset($aExpiredValueHighlight) && in_array($sField, $aExpiredValueHighlight) && $sValue != '&nbsp;') {
					$bExpired  = (strtotime($aData[$sField])-strtotime('now') < 0 ? true : false); // expired
					$sValue = "<span class='".($bExpired ? 'expired-value' : 'not-expired-value')."'>$sValue</span>";
				}
			
			} else {
				if (!is_array($aData) || !isset($aData[$sField]) || empty($aData[$sField]))  {
					$sValue = ($sAction != 'edit' && is_allowed('edit', $iFieldAccessLvl) ? '&nbsp;' : '');
				} else {
					if (fnCheckFieldsDataType($sField, 'currency')) {
						$sValue = number_format($aData[$sField], (intval($aData[$sField]) != $aData[$sField] ? 2 : 0), ',', ($sAction == 'edit' && is_allowed('edit', $iFieldAccessLvl) ? '' : '.'));
					} else {
						$sValue = $aData[$sField];
					}
				}
			
			}
			
			$html .= "<label for='$sField'>".$sLabel."</label>";
			$html .= 
				($sAction == 'edit'  && is_allowed('edit', $iFieldAccessLvl) ?
					"<input name='$sField' id='$sField' type='$sType' value=\"$sValue\" ".
						(fnCheckFieldsDataType($sField, 'date') ? "class='datepicker'" : '').
						" size='$sSize' $sMore>" : 
					"<span id='$sField'>$sValue</span>");
			$html .= "<label for='$sField' class='error'>Inserire $sLabel!</label>";
		
		} else  {
			$html .= '&nbsp;';
		
		} 
		
		return $html;	
	}	
	
	
	/**
	 * fnTextareaInput
	 * <textarea>
	 * 
	 * @param $sField	utilizzato per gli attributi 'name' e 'id' del campo di input
	 *
	 */	
	function fnTextareaInput ($sField, $sLabel, $aData, $sWidth='95%', $sHeight='4.5em', $bTinyMce=false, $sMore='')  {	
				
		global $sAction, $sViewItemLink, $iTab;
		
		$iAccessLvl = fnGetAccessLvl();
		$iFieldAccessLvl = fnFieldAccessLvl($iAccessLvl, $sViewItemLink, $iTab, $sField);
		
		$html = '';
		
		if (is_allowed('view', $iFieldAccessLvl)) {
			
			if (!is_array($aData) || !isset($aData[$sField]) || is_null($aData[$sField]) || empty($aData[$sField])) {
				$sValue = ($sAction != 'edit' ? '&nbsp;' : '');
			} else  {
				$sValue = $aData[$sField];
			}			
			
			$html .= "<label for='$sField'>".$sLabel."</label>";
			$html .= "<label for='$sField' class='error'>Inserire $sLabel!</label>";
			$html .= (($sAction == 'edit' && is_allowed('edit',$iFieldAccessLvl)) || $bTinyMce ?
						"<textarea name='$sField' id='$sField' style='width:$sWidth; height:$sHeight;' $sMore".
							($bTinyMce ?
								"class=".
									($sAction == 'edit' && is_allowed('edit',$iFieldAccessLvl) ?
										"mceEditor" :
										"mceViewer") :
								'').
							" >".$sValue."</textarea>" :
						"<div style='width:$sWidth; min-height:$sHeight;'>".($sValue == '' ?
							'&nbsp;' :
							impress2view_id(nl2br($sValue)))."</div>");	
		} else  {
			$html .= '&nbsp;';
		} 
		
		if (is_allowed('view', $iFieldAccessLvl)) {
		
			global $sHeadContent;
			
			$pos = strpos(strtolower($sHeadContent),strtolower('jquery.tinymce.js'));
			
			if($pos === false) {
				$sHeadContent .= "
					<!-- Load tinyMCE jQuery build -->
					<script type='text/javascript' src='../include/tiny_mce/jquery.tinymce.js'></script> ";	
			}
				
			global $sJsDocumentReady;

			if ($sAction == 'edit' && is_allowed('edit',$iFieldAccessLvl)) {
			
				$pos = strpos(strtolower($sJsDocumentReady),strtolower("$('textarea.mceEditor').tinymce({"));
			
				if ($pos == false) {
			
					$sJsDocumentReady .= "			
							$('textarea.mceEditor').tinymce({
								// Location of TinyMCE script
								script_url : '../include/tiny_mce/tiny_mce.js',
								// General options
								theme : 'advanced',
								// Theme options
								theme_advanced_buttons1 : 'bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,separator,undo,redo,separator,cleanup,separator,forecolor,backcolor,separator,charmap',
								theme_advanced_buttons2 : '', theme_advanced_buttons3 : '', theme_advanced_buttons4 : '',
								theme_advanced_toolbar_location : 'top',
								theme_advanced_toolbar_align : 'left',
								theme_advanced_resizing : false
							}); ";
				}
			
			} else {
				
				$pos = strpos(strtolower($sJsDocumentReady),strtolower("$('textarea.mceViewer').tinymce({"));
			
				if ($pos == false) {
				
					$sJsDocumentReady .= "		
						$('textarea.mceViewer').tinymce({
							// Location of TinyMCE script
							script_url : '../include/tiny_mce/tiny_mce.js',
							// General options
							theme : 'advanced',
							readonly : true
						}); ";
				}
			
			}
		}
		
		return $html;	
	}


	/**
	 * fnCheckboxInput
	 * <input type='checkbox'>
	 *
	 * @param $sField	utilizzato per gli attributi 'name' e 'id' del campo di input
	 *
	 */
	function fnCheckboxInput ($sField, $sLabel, $aData, $sChkValue='1', $sMore='')  {

		global $sAction, $sViewItemLink, $iTab;
			
		$iAccessLvl = fnGetAccessLvl();
		$iFieldAccessLvl = fnFieldAccessLvl($iAccessLvl, $sViewItemLink, $iTab, $sField);

		$html = '';

		if (is_allowed('view', $iFieldAccessLvl)) {
			if (!is_array($aData) || !isset($aData[$sField]) || empty($aData[$sField]))  {
				$sValue = (is_numeric($sChkValue) ? 0 : '');
			} else  {
				$sValue = $aData[$sField];
			}	
			$html .= "<label for='$sField'>$sLabel</label>";
			$html .= "<label for='$sField' class='error'>Campo obbligatorio!</label>";
			
			$sFilename = "./images/".strtolower(substr($sField,1));
			if (!file_exists($sFilename."_on.png") || !file_exists($sFilename."_off.png")) {
				$sFilename = "../themes/common/images/wcheck";
			}

			global $iView;
			
			$html .= 
				($sAction == 'edit' && is_allowed('edit', $iFieldAccessLvl) ?
					"<input type='checkbox' name='$sField' id='$sField' value='$sChkValue' ".((is_numeric($sChkValue) && $sValue == $sChkValue ?
							true :
							(is_string($sChkValue) && strcasecmp($sValue, $sChkValue) == 0 ?
								true :
								false)) ? 'checked' : '')." $sMore />" :
					"<img border='0' src='$sFilename".((is_numeric($sChkValue) && $sValue == $sChkValue ?
							true :
							(is_string($sChkValue) && strcasecmp($sValue, $sChkValue) == 0 ?
								true :
								false))  ? "_on" : "_off").".png' title=\"".strip_tags($sLabel)."\" alt=\"".strip_tags($sLabel)."\" style='vertical-align: middle;'>");
			$html .= "</div>";
		} else  {
			$html .= '&nbsp;';
		} 
		return $html;	
	}	

	/**
	 * fnCheckbox
	 * <img class='ui-toggable'>
	 *
	 * @param $sField	utilizzato per gli attributi 'name' e 'id' del campo di input
	 *
	 */
	function fnCheckbox ($sField, $sLabel, $aData, $sChkValue='1', $sMore='')  {

		global $sAction, $sViewItemLink, $iTab;
		
		$iAccessLvl = fnGetAccessLvl();
		$iFieldAccessLvl = fnFieldAccessLvl($iAccessLvl, $sViewItemLink, $iTab, $sField);

		$html = '';

		if (is_allowed('view', $iFieldAccessLvl)) {
			
			if (!is_array($aData) || !isset($aData[$sField]) || empty($aData[$sField]))  {
				$sValue = (is_numeric($sChkValue) ? 0 : '');
			} else  {
				$sValue = $aData[$sField];
			}	
			
			$html .= "<label for='$sField'>$sLabel</label>";
			
			$sFilename = "./images/".strtolower(substr($sField,1));
			if (!file_exists($sFilename."_on.png") || !file_exists($sFilename."_off.png")) {
				$sFilename = "../themes/common/images/wcheck";
			}

			global $iView;

			$html .=	"<img border='0' id='$sField' src='$sFilename".((is_numeric($sChkValue) && $sValue == $sChkValue ?
							true :
							(is_string($sChkValue) && strcasecmp($sValue, $sChkValue) == 0 ?
								true :
								false))  ? "_on" : "_off").".png' ".(is_allowed('edit', $iFieldAccessLvl) && !empty($iView) ? "class='ui-toggable' sField='$sField'" : '')." title=\"".strip_tags($sLabel)."\" alt=\"".strip_tags($sLabel)."\" style='vertical-align: middle;'>";
			$html .= "</div>";
		} else  {
			$html .= '&nbsp;';
		} 
		return $html;	
	}	
		
	/**
	 * fnSelectInput
	 * <input type='select'>
	 *  
	 * @param $sField				utilizzato per gli attributi 'name' e 'id' del campo di input
	 * @param $sOptionEmptyLabel	descrizione per <option value=''>$sOptionEmptyLabel</option>;
	 * @param $sOptionType			se == 'index' => 	<option value='$sKey'>$sOption<option>
	 *								se == 'text'  =>	<option value='$sOption'>$sOption</option>
	 */
	
	function fnSelectInput ($sField, $sLabel, $aData, $aOptions=array(''), $sOptionType='text', $sOptionEmptyValue='', $sOptionEmptyLabel='n/d', $sMore='') {
		
		global $sAction, $sViewItemLink, $iTab;
		
		$iAccessLvl = fnGetAccessLvl();
		$iFieldAccessLvl = fnFieldAccessLvl($iAccessLvl, $sViewItemLink, $iTab, $sField);

		$html = '';

		if (is_allowed('view',$iFieldAccessLvl)) {
			if (!is_array($aData) || !isset($aData[$sField]) || is_null($aData[$sField])) {
				$sValue = ($sAction != 'edit' ? '&nbsp;' : '');
			} else  {
				$sValue = $aData[$sField];
			}	
			
			$html .= "<label for='$sField'>$sLabel</label>";
			if (empty($aOptions)) {
				$html .= "<select id='$sField' name='$sField' disabled><option value=''>Opzione non disponibile</options></select>";
			
			} else if ($sOptionType == 'text') {
				if ($sAction == 'edit' && is_allowed('edit',$iFieldAccessLvl))  {
					$html .= "<select id='$sField' name='$sField' $sMore >";
					$html .= (!empty($sOptionEmptyLabel) ? "<option value='$sOptionEmptyValue' ".($sValue == $sOptionEmptyValue ? " selected " : '').">".$sOptionEmptyLabel."</option>" : '');
					foreach ($aOptions as $sOption) {
						$html .= "<option value='".($sOption != 'n/d' ? $sOption : '')."'";
						$html .= ((is_numeric($sOption) && $sValue == $sOption ? true : (strcasecmp($sValue, $sOption)==0 ? true : false)) ? " selected " : '');
						$html .= "> ".$sOption." </option>";
					}
					$html .= "</select>";
				} else {
					$html .= ($sValue== '' ? '&nbsp;' : $sValue);
				}
			
			} else if ($sOptionType == 'index') {
				if ($sAction == 'edit' && is_allowed('edit',$iFieldAccessLvl))  {
					$html .= "<select id='$sField' name='$sField' $sMore >";
					$html .= (!empty($sOptionEmptyLabel) ? "<option value='$sOptionEmptyValue' ". ($sValue == $sOptionEmptyValue ? " selected " : '').">".$sOptionEmptyLabel."</option>" : "");
					foreach ($aOptions as $sKey => $sOption) {
						$html .= "<option value='$sKey'";
						$html .= ((is_numeric($sKey) && $sValue == $sKey ? true : (strcasecmp($sValue, $sKey)==0 ? true : false)) ? " selected " : '');
						$html .= ">&nbsp;".$sOption."&nbsp;</option>";
					}
					$html .= "</select>";
			 	} else {
					$html .= (empty($aData[$sField]) ? '&nbsp;' : (isset($aOptions[$aData[$sField]]) ? $aOptions[$aData[$sField]] : $aData[$sField]));
			 	}
			
			}
			
			$html .= "<label for='$sField' class='error'>Selezionare $sLabel!</label>";
			
		} else  {
			$html .= '&nbsp;';
		} 			
		
		return $html;
	}

	/**
	 *
	 * fnSelOptionsFromResources()
	 *
	 */
	function fnSelOptionsFromDb ($sSelectFrom, $sOptionText, $sOptionIndex, $sWhere=' 1 ', $sReferenceField) {
		
		if (!empty($sReferenceField)) {
			global $aData;
			if (isset($aData[$sReferenceField]) && !empty($aData[$sReferenceField])) {
					$sWhere .= " OR `$sOptionIndex`='".$aData[$sReferenceField]."' ";
			}
		}

		$iMaxChar = 65; // massima lunghezza di una stringa di un campo <option>
		
		$aOptions = array();
		
		$sQuery = " SELECT $sOptionIndex as `iIndex`, $sOptionText as `sOptionText` FROM `$sSelectFrom`
					WHERE $sWhere
					ORDER BY `sOptionText` ";
		$rResult = custom_mysql_query($sQuery, 'fnSelOptionsFromDb()');
	   	if (mysql_num_rows($rResult) > 0) {
	   		while ($aRow = mysql_fetch_array($rResult)) {
	   			$sValue = (strlen($aRow['sOptionText'])>$iMaxChar ? substr($aRow['sOptionText'],0,$iMaxChar-4)."..." : $aRow['sOptionText']);
	       		$aOptions[$aRow['iIndex']] = $sValue;
	   		}
	   	}

		return $aOptions;
	}
	
	/**
	 *
	 * fnSelOptionsFromResources()
	 *
	 */
	function fnSelOptionsFromResources ($sResourceType, $sShow='1', $sReferenceField='') {
		
		// $sShow == 1 -- solo risorse 'visibili'
		// $sShow == 0 -- solo risorse 'invisibili'
		// $sShow == '' -- tutte le risorse (sia visibili che invisibility)
		
		switch ($sShow) {
			case '1':
			case '0':
				$sShow = " AND `iShow`='$sShow' ";
				break;
			default:
				$sShow = '';
				break;
		}
		
		if (!empty($sReferenceField)) {
			global $aData;
			if (isset($aData[$sReferenceField]) && !empty($aData[$sReferenceField])) {
				if (empty($sShow))
					$sShow = " OR `id`='".$aData[$sReferenceField]."' ";
				else
					$sShow = " AND (".substr($sShow, 4)." OR `id`='".$aData[$sReferenceField]."') ";
			}
		}

		$iMaxChar = 65; // massima lunghezza di una stringa di un campo <option>
		
		$aOptions = array();
		
		$sQuery = "SELECT `id`, `sDescription` FROM `resources` WHERE `sType`='$sResourceType' $sShow ORDER BY `sDescription` ASC";
		$rResult = custom_mysql_query($sQuery, 'fnSelectInputResourcesOptions()');
	   	if (mysql_num_rows($rResult) > 0) {
	   		while ($aRow = mysql_fetch_array($rResult)) {
	   			$sValue = (strlen($aRow['sDescription'])>$iMaxChar ? substr($aRow['sDescription'],0,$iMaxChar-4)."..." : $aRow['sDescription']);
	       		$aOptions[$aRow['id']] = $sValue;
	   		}
	   	}

		return $aOptions;
	}

	/**
	 *
	 * fnColorRating()
	 *
	 */
	 function fnColorRating ($sField, $sLabel, $aData, $aValues = array('3'=>"Bassa priorità", '2'=>"Media priorità", '1'=>"Alta priorità")) {
		
		global $sAction, $sViewItemLink, $iTab;
		
		$iAccessLvl = fnGetAccessLvl();
		$iFieldAccessLvl = fnFieldAccessLvl($iAccessLvl, $sViewItemLink, $iTab, $sField);

		$html = '';
		
		if (is_allowed('view', $iFieldAccessLvl)) {
		
			if (!is_array($aData) || !isset($aData[$sField]) || empty($aData[$sField]) || !isset($aValues[$aData[$sField]]))  {
				$sValue = '';
			} else {
				$sValue = $aData[$sField];
			}
			
			$html .= "<label for='$sField'>$sLabel</label>";
			$html .= "<label for='$sField' class='error'>Selezionare $sLabel!</label>";
			
			$html .= "<ul id='color-rating'>";
			
			foreach ($aValues as $sKey => $value) {
				$html .= "<li><a $sField='$sKey' href='#'>$value</a></li>";
			}
			
			$html .= "</ul>";
				
			$html .= "<span id='color-rating-info'>".($sValue != '' ? $aValues[$aData[$sField]] : '&nbsp;')."</span>";
			$html .= "<input type='hidden' id='$sField' name='$sField' value='$sValue'>";
			
		} else  {
			$html .= '&nbsp;';
		} 
		
		global $iView;
		global $sViewItemLink;
		global $sAPP;
		
		global $sHeadContent;
		
	 	$sHeadContent .= "
			<script src='../include/sjquery.color.js' type='text/javascript' language='javascript'></script> ";
			
		global $sJsDocumentReady;
		
		$sJsDocumentReady .= "					
					// Array with the colours
					var aColours = { '3':'3bad54', '2':'ecdb00', '1':'bd2c33', '9':'bd2c33' };
					
					// Variable to set the duration of the animation
					var iAnimationTime = 180;
	
					fnColourizeItems($('#$sField').attr('value'));
					
					// Function to colorize the right ratings
					function fnColourizeItems (sValue) {
						
						var bColourizeItem = (sValue != '' ? true : false);
						
						$(' #color-rating li a').each(function() {
							
							if (bColourizeItem) {
								$(this).stop().animate({ backgroundColor : '#' +  aColours[sValue] } , iAnimationTime);
							} else {
								$(this).stop().animate({ backgroundColor : '#333' } , iAnimationTime);
							}
							if($(this).attr('$sField') == sValue) {
								bColourizeItem = false;
							}
							
						});
					}; ".(is_allowed('edit', $iFieldAccessLvl) ? "

					// Handle the hover events
					$(' #color-rating li a').hover(function() {
		
						// Empty the rating info box and fade in
						$('#color-rating-info')
							.empty()
							.stop()
							.animate({ opacity : 1 }, iAnimationTime);
		
						// Add the text to the rating info box
						$('#color-rating-info').html($(this).html());
						
						// Call the colourize function with the given index
						fnColourizeItems($(this).attr('$sField'));
					
					}, function() {
						
						// Restore the rating information box
						$('#color-rating-info').html($('a[$sField=' + $('input#$sField').attr('value') + ']').html());
						
						// Restore all the rating to their original colours
						fnColourizeItems($('input#$sField').attr('value'));
						
					});
	
					// Prevent the click event and show the rating
					$(' #color-rating li a').click(function(e) {
						e.preventDefault();
						$.getJSON('../include/toggle.php', {'sAction': 'toggle',
															'sField': '$sField',
															'sValue': $(this).attr('$sField'),
															'iView': '$iView',
															'sTable': '',
															'sViewItemLink': '$sViewItemLink',
															'sAPP': '$sAPP'	}, function (json) {
							if (json[0].sAction=='toggle' && json[0].sError=='') {
								$('input#$sField').attr('value', json[0].$sField);
							}
							fnColourizeItems($('#$sField').attr('value'));
							$('#color-rating-info').html($('a[$sField=' + $('#$sField').attr('value') + ']').html());
						});						
					}); " : '');
					
		return $html;	
	}	

	
	/**
	 *
	 * fnStarRating()
	 *
	 */
	function fnStarRating ($sField, $sLabel, $aData, $aValues = array('3'=>"Bassa priorità", '2'=>"Media priorità", '1'=>"Alta priorità")) {
		
		global $sAction, $sViewItemLink, $iTab;
		
		$iAccessLvl = fnGetAccessLvl();
		$iFieldAccessLvl = fnFieldAccessLvl($iAccessLvl, $sViewItemLink, $iTab, $sField);

		$html = '';
		
		if (is_allowed('view', $iFieldAccessLvl)) {
		
			if (!is_array($aData) || !isset($aData[$sField]) || empty($aData[$sField]) || !isset($aValues[$aData[$sField]]))  {
				$sValue = '';
			} else {
				$sValue = $aData[$sField];
			}
			
			$html .= "<label for='$sField'>$sLabel</label>";
			$html .= "<label for='$sField' class='error'>Selezionare $sLabel!</label>";
		
			foreach ($aValues as $sKey => $value) {
				$html .= "<input class='hover-star' type='radio' name='$sField' value='$sKey' title='$value' ".
				(($sAction == 'edit'  && is_allowed('edit',$iFieldAccessLvl)) ? '' : " disabled='disabled' ").
				(($sValue == $sKey) ? " checked='checked' " : '')." />";
			}
			
			$html .= "<span id='hover-star-info' style='margin:0 0 0 12px; font-size: 88%; font-weight: bold;'>".
				(isset($aValues[$sValue]) && $sAction != 'edit' ? ($aValues[$sValue]) : '&nbsp;')."</span>";
			
		} else  {
			$html .= '&nbsp;';
		} 
		
		global $sHeadContent;
		
	 	$sHeadContent .= "
			<!--// jQuery Star Rating Plugin - plugin-specific resources //-->
	 		<script src='../include/star-rating/jquery.form.js' type='text/javascript' language='javascript'></script>
			<script src='../include/star-rating/jquery.MetaData.js' type='text/javascript' language='javascript'></script>
	 		<script src='../include/star-rating/jquery.rating.js' type='text/javascript' language='javascript'></script>
	 		<link href='../include/star-rating/jquery.rating.css' type='text/css' rel='stylesheet'/> ";		
		
		global $sJsDocumentReady;
		
		$sJsDocumentReady .= "	
					$('.hover-star').rating({
					  	focus: function(value, link){
					    	// 'this' is the hidden form element holding the current value
					    	// 'value' is the value selected
					    	// 'element' points to the link element that received the click.
					    	var tip = $('#hover-star-info');
					    	tip[0].data = tip[0].data || tip.html();
					    	tip.html(link.title || 'value: '+value);
					  	},
					  	blur: function(value, link){
					    	var tip = $('#hover-star-info');
					    	$('#hover-star-info').html(tip[0].data || '');
					  	}
					}); ";
					
		return $html;	
	}	

?>